package com.ebt.m.wiki;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.activity.BaseToolBarActivity;
import com.ebt.m.commons.model.data.BaseDataResult;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.config.CustomerConfig;
import com.ebt.m.data.bean.CommonCustomer;
import com.ebt.m.data.bean.EnumSex;
import com.ebt.m.data.entity.ProductBridgeObj;
import com.ebt.m.data.entity.ProductInfo;
import com.ebt.m.data.middle.InsuredPerson;
import com.ebt.m.data.middle.ProductConstraint;
import com.ebt.m.data.provider.WikiProvider;
import com.ebt.m.homepage.SpinnerMenu;
import com.ebt.m.proposal_v2.utils.EnumProfession;
import com.ebt.m.proposal_v2.utils.ProposalUtils;
import com.ebt.m.utils.TimeUtils;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.view.DialogInsuranceAgePicker;
import com.ebt.m.widget.BaseAlertDialog;
import com.ebt.m.wiki.event.EData4Cal;
import com.ebt.m.wiki.event.EOnCalculatorChange;
import com.ebt.m.wiki.view.AutoViewsFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


/**
 * @author Damon.Han
 * @Description: 计算器
 * @date 2015年12月24日 上午10:53:34
 */
public class ActWikiCalc extends BaseToolBarActivity implements OnClickListener {
    public static final String TAG = "ActWikiCalc";
    private ProductBridgeObj mProductObj;
    private AutoViewsFactory autoViewsFactory;
    private TextView c_age;
    private RadioButton rb_man;
    private RadioButton rb_female;
    private ImageView img_portrait;
    private ProductInfo mProductInfo;
    private InsuredPerson person;
    private Button mActionSure;
    private Button mActionCancel;
    private SpinnerMenu mSpinner;
    private LinearLayout mProContainer;
    private TextView mProLabel;
    private ToggleButton mToggleImg;
    private ProgressBar progress_bar;
    private Context mContext;
    private boolean isOkFinished;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.wiki_calc);
        getWindow().setLayout(WindowManager.LayoutParams.FILL_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        getWindow().setGravity(Gravity.BOTTOM);
        progress_bar = findViewById(R.id.progress_bar);
        this.person = (InsuredPerson) getIntent().getSerializableExtra("person");
        this.mProductInfo = (ProductInfo) getIntent().getSerializableExtra("mProductInfo");
        initView();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void receiveData(EData4Cal event) {
        String rateType = mProductInfo.getRateType();
        this.mProductObj = event.mProductObj;
        mProductObj.saveOldData();
        initData();
    }

    /**
     * 获取rate
     *
     * @param age
     * @param sex
     * @param productId
     */
    private void getOnlineRate(int age, int sex, int productId) {
        Logger.e("getOnlineRate");
        AppInitService.getEbtApi().getRate(productId, age + "", sex + "")
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<BaseDataResult<HashMap<String, Double>>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseDataResult<HashMap<String, Double>> hashMapBaseDataResult) {
                HashMap<String, Double> rateHashMap = hashMapBaseDataResult.getData();
                mProductObj.getInsuranceObj().setRateHashMap(rateHashMap);
                mProductObj.setPerson(person);
                refreshControllerViews();
            }

            @Override
            public void onError(Throwable e) {
                progress_bar.setVisibility(View.GONE);
            }

            @Override
            public void onComplete() {
                progress_bar.setVisibility(View.GONE);
            }
        });
    }

    private void initData() {
        int[] minAges = ProposalUtils.getAges(mProductObj.getmProduct().MinAge);
        int[] maxAges = ProposalUtils.getAges(mProductObj.getmProduct().MaxAge);
        ProductConstraint productAgeConstraint = new ProductConstraint(person.age, minAges, maxAges, mProductObj.getmProduct().AccSex, mProductObj.getmProduct().AccOccupation);
        person.productAgeConstraint = productAgeConstraint;
        setTitle(mProductObj.getProductName() + "");
        toolbar.setBackgroundColor(getResources().getColor(R.color.common_bg_bar));
        c_age.setText(person.age + "岁");
        if (person != null && person.productAgeConstraint != null && person.productAgeConstraint.accSex != 0) {
            int sex = Integer.parseInt(person.sex);
            if (sex == EnumSex.FEMALE.ordinal() && 1 == person.productAgeConstraint.accSex) {
                //仅女性可选
                rb_man.setEnabled(false);
                rb_man.setVisibility(View.GONE);
                rb_female.setChecked(true);
            }

            if (sex == EnumSex.MAN.ordinal() && 2 == person.productAgeConstraint.accSex) {
                //仅男性可选
                rb_female.setEnabled(false);
                rb_female.setVisibility(View.GONE);
                rb_man.setChecked(true);
            }
        } else {
            if (Integer.parseInt(person.sex) == EnumSex.FEMALE.ordinal()) {
                rb_female.setChecked(true);
            } else {
                rb_man.setChecked(true);
            }
        }
        List<Integer> careerIdlist = new ArrayList<Integer>();
        if (productAgeConstraint == null) {
            for (int i = EnumProfession.ONE.value(); i <= EnumProfession.SIX.value(); i++) {
                careerIdlist.add(i);
            }
        } else {
            int maxOccupation = productAgeConstraint.accOccupation;
            if (maxOccupation == 0) {
                for (int i = EnumProfession.ONE.value(); i <= EnumProfession.SIX.value(); i++) {
                    careerIdlist.add(i);
                }
            } else {
                for (int i = EnumProfession.ONE.value(); i <= maxOccupation; i++) {
                    careerIdlist.add(i);
                }
            }
        }
        String[] array = mContext.getResources().getStringArray(R.array.common_professional);
        List<String> realList = new ArrayList<>(Arrays.asList(array));
        Iterator iterator = realList.iterator();
        int i = 0;
        while (iterator.hasNext()) {
            i++;
            iterator.next();
            if (!careerIdlist.contains(i)) {
                iterator.remove();
            }
        }
        String[] newArray = realList.toArray(new String[0]);
        initProLabel(newArray);
        //initSpinner(newArray);
        setPortrait();
    }

    private void initSpinner(String[] newArray) {
        if (mSpinner == null) {
            mSpinner = new SpinnerMenu(this, mProContainer, newArray, person.profession - 1);
            mSpinner.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mToggleImg.setChecked(false);
                }
            });
            mSpinner.setOnTypeSelectedListener(new SpinnerMenu.OnTypeSelectedListener() {
                @Override
                public void onTypeSelected(int position, String title) {
                    person.profession = position + 1;
                    changePerson();
                    mProLabel.setText(newArray[position]);
                    mSpinner.dismiss();
                }
            });
            mSpinner.popShow();
        } else {
            if (mSpinner.isShowing()) {
                mSpinner.dismiss();
            } else {
                mSpinner.popShow(person.profession - 1);
            }

        }
        mToggleImg.setChecked(mSpinner.isShowing());
    }

    private void initProLabel(String[] newArray) {
        String pro = newArray[person.profession - 1];
        mProContainer = (LinearLayout) findViewById(R.id.pro_container);
        mProLabel = (TextView) findViewById(R.id.pro_label);
        mToggleImg = (ToggleButton) findViewById(R.id.toggle_bt);
        mProLabel.setText(pro);
        mProContainer.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                initSpinner(newArray);
            }
        });
    }

    private void initView() {
        img_portrait = (ImageView) findViewById(R.id.img_portrait);
        c_age = (TextView) findViewById(R.id.c_age);
        rb_man = (RadioButton) findViewById(R.id.rb_man);
        rb_female = (RadioButton) findViewById(R.id.rb_female);
        mActionSure = (Button) findViewById(R.id.btn_sure);
        mActionCancel = (Button) findViewById(R.id.btn_cancel);
        mActionCancel.setOnClickListener(this);
        mActionSure.setOnClickListener(this);
        ViewGroup container = (ViewGroup) findViewById(R.id.wiki_tab2_scrollcontainer);
        autoViewsFactory = new AutoViewsFactory(mContext, container);

        c_age.setOnClickListener(this);
        rb_man.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    person.sex = EnumSex.MAN.ordinal() + "";
                    if (rb_female.isChecked()) {
                        rb_female.setChecked(false);
                    }
                    setPortrait();
                    changePerson();
                }
            }
        });

        rb_female.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    person.sex = EnumSex.FEMALE.ordinal() + "";
                    if (rb_man.isChecked()) {
                        rb_man.setChecked(false);
                    }
                    setPortrait();
                    changePerson();
                }
            }
        });
    }

    /**
     * 更改被保人
     */
    private void changePerson() {
        if (mProductInfo == null) {
            return;
        }
        String rateType = mProductInfo.getRateType();
        if ("object".equalsIgnoreCase(rateType)) {
            getOnlineRate(person.age, Integer.valueOf(person.sex), mProductInfo.ProductId);
        } else {
            mProductObj.setPerson(person);
            refreshControllerViews();
        }
    }

    /**
     * 重新生成选项view
     * （更改被保人属性之后）
     */
    private void refreshControllerViews() {
        autoViewsFactory.generateViews(mProductObj.getInsuranceObj());
    }

    /**
     * 保存常用联系人
     *
     * @param person
     */
    private void saveCommonCustomer(InsuredPerson person) {
        try {
            WikiProvider wikiProvider = new WikiProvider(mContext);
            CommonCustomer commonCustomer = new CommonCustomer();
            commonCustomer.age = person.age;
            commonCustomer.sex = Integer.valueOf(person.sex);
            commonCustomer.pro = person.profession;
            commonCustomer.updateTime = System.currentTimeMillis();
            wikiProvider.saveCommonCustomer(commonCustomer);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setPortrait() {
        int sex = 0;
        try {
            sex = Integer.valueOf(person.sex);
            int resId = CustomerConfig.getPortraitResource(sex, person.age);
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
            img_portrait.setImageResource(resId);
            img_portrait.startAnimation(animation);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 选择年龄
     */
    private void chooseAge() {
        BaseAlertDialog.OnDialogListener mOnDialogListener = new BaseAlertDialog.OnDialogListener() {
            @Override
            public void onConfirmed() {
            }

            @Override
            public void onConfirmed(int intValue) {
                String sAge = String.valueOf(intValue) + "岁";
                person.age = intValue;
                int days = ProposalUtils.getMinAgeDay(mProductInfo);
                if (days > 0 && intValue == 0) {
                    Date bd = TimeUtils.dayPlusOrMinus(TimeUtils.getBirthday(intValue), -days);
                    person.birthday = bd;
                }
                c_age.setText(sAge);
                setPortrait();
                changePerson();
            }
        };
        ProductConstraint productAgeConstraint = person.productAgeConstraint;
        if (productAgeConstraint == null) {
            DialogInsuranceAgePicker mAgePickerDialog = new DialogInsuranceAgePicker(mContext, person.age);
            mAgePickerDialog.setListener(mOnDialogListener);
            mAgePickerDialog.show();
        } else {
            if (productAgeConstraint.minAge == 0) {// 取年不为0，只比较年即年龄
                productAgeConstraint.minAge = DialogInsuranceAgePicker.AGE_PICKER_MIN;
            }
            if (productAgeConstraint.maxAge == 0) {// 取年不为0，只比较年即年龄
                productAgeConstraint.maxAge = DialogInsuranceAgePicker.AGE_PICKER_MAX;
            }
            DialogInsuranceAgePicker mAgePickerDialog = new DialogInsuranceAgePicker(mContext, person.age, productAgeConstraint.minAge, productAgeConstraint.maxAge);
            mAgePickerDialog.setListener(mOnDialogListener);
            mAgePickerDialog.show();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.c_age:
                chooseAge();
                break;
            case R.id.btn_sure:
//                String errorMsg = ProposalUtils.hasMeetWith(person, mProductInfo);
                String errorMsg = ProposalUtils.fitMeetWithIfAge0(person, mProductInfo);

                if (!TextUtils.isEmpty(errorMsg)) {
                    UIHelper.makeToast(mContext, errorMsg, false);
                    return;
                }
                EOnCalculatorChange epc = new EOnCalculatorChange();
                epc.isChanged = true;
                epc.mProductObj = mProductObj;
                epc.optionString = mProductObj.getFavoriteJson();
                EventBus.getDefault().post(epc);
                saveCommonCustomer(person);
                isOkFinished = true;
                finish();
                break;
            case R.id.btn_cancel:
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void finish() {
        if (!isOkFinished) {
            mProductObj.resetData();
        }
        super.finish();
    }

    @Override
    public void onDestroy() {
        mSpinner = null;
        super.onDestroy();
    }
}
